<template>
  <el-container>
    <el-header>
      <el-page-header @back="goBack" title="返回" :content="roomName">
      </el-page-header>
    </el-header>
    <el-row id="usersRow">
      <!-- 用户列表 -->
      <el-popover placement="bottom-start" width="300" trigger="click">
        <el-table :data="userList" :show-header="false">
          <el-table-column>
            <template slot-scope="scope">
              <JwChat-item :config="scope.row" />
            </template>
          </el-table-column>
          <el-table-column width="70">
            <template slot-scope="scope">
              <el-button type="success" v-on:click="removeUserToRoom(scope.row)" size="mini" icon="el-icon-minus"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button slot="reference" v-on:click="getUsersByRoomId" type="info">用户列表</el-button>
      </el-popover>
      <!-- 邀请用户 -->
      <el-popover placement="bottom-start" width="300" trigger="click">
        <el-table :data="allUserList" :show-header="false">
          <el-table-column>
            <template slot-scope="scope">
              <JwChat-item :config="scope.row" />
            </template>
          </el-table-column>
          <el-table-column width="70">
            <template slot-scope="scope">
              <el-button type="success" v-on:click="addUserToRoom(scope.row)" size="mini" icon="el-icon-plus"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button slot="reference" v-on:click="getUsers" type="info">邀请用户</el-button>
      </el-popover>
    </el-row>
    <el-main>
      <JwChat :taleList="list" @enter="bindEnter" @clickTalk="talkEvent" v-model="inputMsg" :toolConfig="tool" width="100%"
        id="myChat">
      </JwChat>


      <!-- 聊天室用户列表弹窗 -->

      <!-- 所有用户列表弹窗(可选择用户加入当前聊天室) -->
    </el-main>
  </el-container>
</template>

<script>
  import {
    checkResData,
    getUserId,
    getUserNickName,
    getUserImg,
    getId
  } from '../utils/selfInfoUtil.js'
  export default {
    // name: 'ChattingRoom',
    data() {
      return {
        userList: [],
        allUserList: [],
        roomName: '',
        roomId: '',
        inputMsg: '',
        list: [],
        tool: {
          callback: this.toolEvent
        }
      }
    },
    created() {
      // 建立websocket连接，用于监听用户被删除
      this.webSokectConnection()
      this.roomName = this.$route.params.roomname
      this.roomId = this.$route.params.roomid
      // 如果传递了未读消息的数量，则从后台获取当前未读消息的数量
      if (this.$route.params.msgCount) {
        this.getMsg(this.$route.params.msgCount)
      }

      // 建立websocket连接
      this.connectWebSocket()
    },
    methods: {
      // 回车触发事件("消息的发送")
      bindEnter(e) {
        const msg = this.inputMsg
        // 通过接口发送消息到 queue
        this.$axios.post('chatting/sendMessage', {
          queueName: this.roomId,
          message: {
            id: getId(),
            fromId: getUserId(),
            nickName: getUserNickName(),
            img: getUserImg(),
            reveType: 2,
            reveId: this.roomId,
            createTime: this.dateFormat(new Date()),
            msgType: 1,
            msgContent: e
          }
        }).then(res => {
          if (checkResData(res.data.code, res.data.success)) {} else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          this.$message.error("服务器溜了！ 已经去抓了")
        })
      },
      // 工具栏插槽
      toolEvent(type, obj) {
        console.log('tools', type, obj)
      },
      // 点击用户头像触发事件
      talkEvent(play) {
        console.log("play", play)
      },
      // 回退
      goBack() {
        this.$router.push('/home')
        // window.history.back(-1);
      },
      // 建立websocket连接
      connectWebSocket() {
        var socket;
        var _this = this;
        if (typeof(WebSocket) == "undefined") {
          console.log("您的浏览器不支持 WebSocket!");
        } else {
          console.log("您的浏览器支持 WebSocket!");
          socket = new WebSocket("ws://localhost:8002/websocket/room/" + this.roomId);
          socket.onopen = function() {
            console.log("聊天室 Websocket 已打开");
            socket.send("这是来自客户端的消息" + location.href + new Date());
          };
          socket.onmessage = function(msg) {
            var strJson = JSON.parse(msg.data)
            let msgObj = {
              "date": strJson.createTime,
              "text": {
                "text": strJson.msgContent
              },
              "mine": false,
              "name": strJson.nickName,
              "img": strJson.img
            }
            if (strJson.fromId == getUserId()) {
              msgObj.mine = true
            }
            _this.list.push(msgObj)
            console.log("list", _this.list)
          }
          socket.onclose = function() {
            console.log("聊天室 Websocket 已经关闭")
          }
          socket.onerror = function() {
            alert("聊天室 Websocket 发生了错误")
          }
        }
      },
      // 时间处理函数 ，格式化时间 YYYY-mm-DD HH:MM:SS
      dateFormat(time) {
        var date = new Date(time);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始的，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      },
      // 获取未读消息
      getMsg(count) {
        this.$axios.post('/room/getMsg', {
            roomId: this.roomId,
            msgCount: count
          })
          .then(res => {
            console.log("未读消息:", res.data)
            if (checkResData(res.data.code, res.data.success)) {
              for (var i = res.data.data.length - 1; i >= 0; i--) {
                // console.log("未读消息",res.data.data)
                let strJson = res.data.data[i]
                let msgObj = {
                  "date": strJson.createTime,
                  "text": {
                    "text": strJson.msgContent
                  },
                  "mine": false,
                  "name": strJson.nickName,
                  "img": strJson.img
                }
                if (strJson.fromId == getUserId()) {
                  msgObj.mine = true
                }
                this.list.push(msgObj)
              }
            } else {
              this.$message.info(res.data.msg)
            }
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 获取当前平台所有用户列表，暂时未考虑分页，本来就不考虑多少用户
      getUsers() {
        this.$axios.post('user/getUsers')
          .then(res => {
            if (checkResData(res.data.code, res.data.success)) {
              let data = res.data.data
              let userList1 = []
              for (var i = 0; i < data.length; i++) {
                let userObj = {
                  userid: data[i].id,
                  img: data[i].img,
                  name: data[i].nickname
                }
                userList1.push(userObj)
              }
              this.allUserList = userList1
            } else {
              this.$message.info(res.data.msg)
            }
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 获取已加入当前聊天室的用户列表
      getUsersByRoomId() {
        this.$axios.post('room/getUsers/' + this.roomId)
          .then(res => {
            if (checkResData(res.data.code, res.data.success)) {
              let data = res.data.data
              let userList1 = []
              for (var i = 0; i < data.length; i++) {
                let userObj = {
                  userid: data[i].id,
                  img: data[i].img,
                  name: data[i].nickname
                }
                userList1.push(userObj)
              }
              this.userList = userList1
            } else {
              this.$message.info(res.data.msg)
            }
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 添加用户到当前聊天室
      addUserToRoom(data) {
        this.$axios.post('room/user/addRoom', {
            roomId: this.roomId,
            userId: data.userid
          })
          .then(res => {
            if (checkResData(res.data.code, res.data.success)) {
              this.$message.success(res.data.msg)
            } else {
              this.$message.info(res.data.msg)
            }
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 移除当前聊天室中的用户
      removeUserToRoom(data) {
        this.$axios.post('room/user/quitRoom', {
            roomId: this.roomId,
            userId: data.userid
          })
          .then(res => {
            this.$message.success(res.data.msg)
            this.getUsersByRoomId()
          })
          .catch(err => {
            this.$message.error("服务器溜了！ 已经去抓了")
          })
      },
      // 建立websocket连接
      webSokectConnection() {
        console.log("one   sfsdfs")
        var socket;
        var _this = this;
        if (typeof(WebSocket) == "undefined") {
          console.log("您的浏览器不支持 WebSocket!");
        } else {
          console.log("您的浏览器支持 WebSocket!");
          socket = new WebSocket("ws://192.168.5.13:8002/websocket/room/tellQuitChattingRoom");
          socket.onopen = function() {
            console.log("Home Websocket 已打开");
            socket.send("这是来自客户端的消息" + location.href + new Date());
          };
          socket.onmessage = function(msg) {
            var strJson = JSON.parse(msg.data)
            if (strJson.userId === getUserId()) {
              socket.close()
              _this.$message.error("您已被 【 "+strJson.nickName+" 】 移出群聊!")
              _this.$router.push(`home`)
            }
            // console.log(_this.tableData)
          }
          socket.onclose = function() {
            console.log("Home Websocket 已经关闭")
          }
          socket.onerror = function() {
            alert("Home Websocket 发生了错误")
          }
        }
      }
    }
  }
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  h1,
  h2 {
    font-weight: normal;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    display: inline-block;
    margin: 0 10px;
  }

  a {
    color: #42b983;
  }

  .el-header,
  .el-page-header {
    text-align: center;
    background-color: #B3C0D1;
    color: #333;
    line-height: 3.75rem;
  }

  .el-main {
    background-color: #E9EEF3;
    color: #333;
  }

  .el-container {
    padding: 0;
    margin: 0;
    min-height: 100vh;
    background-color: #0077AA;
  }

  #myChat {
    padding: 0;
    margin: 0;
    min-height: 85vh;
  }

  #usersRow {
    background-color: #E9EEF3;
    padding-top: 12px;
    margin-bottom: -10px;
    padding-right: 20px;
    text-align: right;
  }
</style>
